import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore(
  'cp-user',
  () => {
    const token = ref() // 从 localStorage 初始化 Token
    const userInfo = ref() // 登录用户信息
    const roles = ref() // 登录用户角色
    const tenant = ref() // 租户信息
    const permissions = ref<Array<string>>([]) // 用户权限编码集合 → 判断按钮权限
    // 设置 用户权限编码集合
    const setPermissions = (newPermissions: Array<string>) => {
      permissions.value = newPermissions
    }

    // 设置 Token
    const setToken = (newToken: any) => {
      token.value = newToken
    }

    // 设置 登录用户信息
    const setUserInfo = (newUserInfo: any) => {
      userInfo.value = newUserInfo
    }

    // 设置 登录用户角色
    const setRoles = (newRoles: any) => {
      roles.value = newRoles
    }

    // 设置 登录租户logo/标题
    const setTenant = (newTenant: any) => {
      tenant.value = newTenant
    }

    // 清除 Token
    const clearToken = () => {
      token.value = undefined
    }

    // 清除 userInfo
    const clearUserInfo = () => {
      userInfo.value = undefined
    }

    // 清除 roles
    const clearRoles = () => {
      roles.value = undefined
    }

    // 清除 tenant
    const clearTenant = () => {
      tenant.value = undefined
    }

    // 检查是否已登录
    const isAuthenticated = () => {
      return !!token.value
    }

    return {
      token,
      userInfo,
      roles,
      tenant,
      permissions,
      setPermissions,
      setToken,
      clearToken,
      setRoles,
      clearRoles,
      setUserInfo,
      clearUserInfo,
      setTenant,
      clearTenant,
      isAuthenticated
    }
  },
  {
    persist: true
  }
)
